import json
import traceback
from datetime import datetime, timedelta
from django.utils import timezone
from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny
from rest_framework.response import Response
import re

from .models import Message, MessageBroadcast, MessageReceipt, Feedback
from users.models import User, Visitor


@api_view(['GET', 'POST'])
def message_list(request):
    """
    获取消息列表或创建新消息。
    """
    if request.method == 'GET':
        try:
            # 获取查询参数
            message_type = request.query_params.get('message_type', None)
            title = request.query_params.get('title', None)
            page = int(request.query_params.get('page', 1))
            size = int(request.query_params.get('size', 10))
            publish_time_param = request.query_params.get('publish_time', None)

            # 构建查询集
            queryset = Message.objects.all()

            if message_type:
                queryset = queryset.filter(message_type=message_type)
            if title:
                queryset = queryset.filter(title__icontains=title)

            # 处理publish_time参数
            if publish_time_param == 'null':
                # 只查询草稿（publish_time为null的消息）
                queryset = queryset.filter(publish_time__isnull=True)
            elif publish_time_param == 'not_null':
                # 只查询已发布的消息（publish_time不为null）
                queryset = queryset.filter(publish_time__isnull=False)

            # 按创建时间倒序排序，确保草稿显示最新的在前面
            if publish_time_param == 'null':
                queryset = queryset.order_by('-created_at')
            else:
                # 对于已发布消息，仍按发布时间排序
                queryset = queryset.order_by('-publish_time')

            # 获取总数
            total = queryset.count()

            # 分页处理
            start = (page - 1) * size
            end = start + size
            paginated_messages = queryset[start:end]

            # 构建响应数据
            messages = []
            for message in paginated_messages:
                # 计算阅读量 - 查询该消息有多少条已读回执
                read_count = MessageReceipt.objects.filter(
                    message_id=message.message_id,
                    read_status=True
                ).count()

                # 获取广播状态
                broadcast_status = '待处理'  # 默认值
                try:
                    broadcast = MessageBroadcast.objects.get(message_id=message.message_id)
                    broadcast_status = broadcast.status
                except MessageBroadcast.DoesNotExist:
                    pass

                messages.append({
                    'id': message.message_id,
                    'title': message.title,
                    'message_type': message.message_type,
                    'publish_time': message.publish_time.strftime(
                        '%Y-%m-%d %H:%M:%S') if message.publish_time else None,
                    'valid_from': message.valid_from.strftime('%Y-%m-%d %H:%M:%S') if message.valid_from else None,
                    'valid_until': message.valid_until.strftime('%Y-%m-%d %H:%M:%S') if message.valid_until else None,
                    'status': '已发布' if message.publish_time else '草稿',
                    'broadcast_status': broadcast_status,
                    'read_count': read_count,
                    'created_at': message.created_at.strftime('%Y-%m-%d %H:%M:%S') if message.created_at else None,
                    'updated_at': message.updated_at.strftime('%Y-%m-%d %H:%M:%S') if message.updated_at else None
                })

            return Response({
                'code': 200,
                'message': '获取通知列表成功',
                'data': {
                    'total': total,
                    'list': messages,
                    'page': page,
                    'size': size,
                    'pages': (total + size - 1) // size  # 总页数计算
                }
            })
        except Exception as e:
            return Response({
                'code': 500,
                'message': '服务器在处理消息列表时发生错误',
                'error': str(e),
                'trace': traceback.format_exc()
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'POST':
        try:
            # 获取请求数据
            title = request.data.get('title')
            content = request.data.get('content')
            message_type = request.data.get('message_type')
            valid_from = request.data.get('valid_from')
            valid_until = request.data.get('valid_until')
            target_groups = request.data.get('target_groups', [])
            specific_users = request.data.get('specific_users', [])

            # 打印接收到的原始数据以便调试
            print("接收到的请求数据:")
            print(f"标题: {title}")
            print(f"类型: {message_type}")
            print(f"开始时间: {valid_from}")
            print(f"结束时间: {valid_until}")
            print(f"目标群体: {target_groups}")
            print(f"特定用户: {specific_users}")

            # 检查是否为草稿模式
            is_draft = request.data.get('is_draft', False)

            # 验证必填字段
            if not title:
                return Response({
                    'code': 400,
                    'message': '标题不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            if not content:
                return Response({
                    'code': 400,
                    'message': '内容不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            if not message_type:
                return Response({
                    'code': 400,
                    'message': '消息类型不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 如果不是草稿，检查目标受众
            if not is_draft and not target_groups and not specific_users:
                return Response({
                    'code': 400,
                    'message': '请至少选择一个目标群体或特定用户'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 获取当前用户作为发送者
            sender_user_id = None
            if hasattr(request, 'user') and hasattr(request.user, 'user_id'):
                sender_user_id = request.user.user_id

            now = timezone.now()

            # 改进日期处理逻辑
            try:
                if valid_from:
                    # 尝试解析ISO格式日期字符串
                    if 'T' in valid_from:
                        final_valid_from = timezone.datetime.fromisoformat(valid_from.replace('Z', '+00:00'))
                    else:
                        final_valid_from = timezone.datetime.strptime(valid_from, '%Y-%m-%d %H:%M:%S')
                else:
                    final_valid_from = now
                
                if valid_until:
                    # 尝试解析ISO格式日期字符串
                    if 'T' in valid_until:
                        final_valid_until = timezone.datetime.fromisoformat(valid_until.replace('Z', '+00:00'))
                    else:
                        final_valid_until = timezone.datetime.strptime(valid_until, '%Y-%m-%d %H:%M:%S')
                else:
                    # 如果有效期结束时间未提供，则默认为开始时间之后7天
                    final_valid_until = final_valid_from + timedelta(days=7)
            except Exception as e:
                print(f"日期解析错误: {e}")
                # 如果日期解析失败，使用默认值
                final_valid_from = now
                final_valid_until = now + timedelta(days=7)

            # 创建新消息
            message = Message(
                title=title,
                content=content,
                message_type=message_type,
                sender_user_id=None,  # 先设为None
                publish_time=None if is_draft else now,  # 草稿模式下publish_time为None
                valid_from=final_valid_from,
                valid_until=final_valid_until,
                created_at=now,
                updated_at=now
            )
            
            # 如果有发送者ID，单独设置
            if sender_user_id:
                try:
                    sender_user = User.objects.get(user_id=sender_user_id)
                    message.sender_user = sender_user
                except User.DoesNotExist:
                    # 如果找不到用户，不设置发送者
                    pass
                
            message.save()

            # 创建消息广播记录
            target_criteria = {
                'target_groups': target_groups,
                'specific_users': specific_users
            }

            # 创建广播记录，根据是否为草稿设置不同的状态和处理日志
            now_str = now.strftime('%Y-%m-%d %H:%M:%S')
            if is_draft:
                broadcast_status = '待处理'
                processing_log = f"[{now_str}] 创建草稿消息，等待发布"
            else:
                broadcast_status = '已发布'
                processing_log = f"[{now_str}] 消息已创建并发布，目标受众: {len(target_groups)}个群体, {len(specific_users)}个特定用户"

            broadcast = MessageBroadcast(
                message_id=message.message_id,
                target_criteria=target_criteria,
                status=broadcast_status,
                processing_log=processing_log,
                completed_at=now if not is_draft else None  # 只有非草稿才设置完成时间
            )
            broadcast.save()

            # 如果不是草稿且有特定用户，创建消息接收记录
            if not is_draft and specific_users:
                for user_id_str in specific_users:
                    try:
                        # 检查不同格式的用户ID
                        if isinstance(user_id_str, str) and user_id_str.startswith('user'):
                            # 尝试提取数字部分，处理"user1", "user_1"等格式
                            numeric_part = re.search(r'\d+', user_id_str)
                            if numeric_part:
                                user_id = int(numeric_part.group())
                                receipt = MessageReceipt(
                                    message_id=message.message_id,
                                    broadcast_id=broadcast.broadcast_id,
                                    user_id=user_id,
                                    read_status=False
                                )
                                receipt.save()
                        elif isinstance(user_id_str, str) and user_id_str.startswith('comp'):
                            # 对企业用户进行特殊处理
                            # 这里可以根据企业ID查找该企业下的所有用户
                            pass  # 企业用户处理逻辑待实现
                        else:
                            # 直接尝试将整个ID作为用户ID使用
                            try:
                                if isinstance(user_id_str, int):
                                    user_id = user_id_str
                                else:
                                    user_id = int(user_id_str)
                                receipt = MessageReceipt(
                                    message_id=message.message_id,
                                    broadcast_id=broadcast.broadcast_id,
                                    user_id=user_id,
                                    read_status=False
                                )
                                receipt.save()
                            except (ValueError, TypeError):
                                pass  # 忽略无法处理的用户ID格式
                    except Exception:
                        pass  # 忽略处理单个用户ID时的错误

            return Response({
                'code': 201,
                'message': '消息创建成功',
                'data': {
                    'id': message.message_id,
                    'title': message.title,
                    'publish_time': message.publish_time.strftime(
                        '%Y-%m-%d %H:%M:%S') if message.publish_time else None,
                    'target_groups': target_groups,
                    'specific_users': specific_users,
                    'is_draft': is_draft
                }
            }, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({
                'code': 500,
                'message': '服务器在创建消息时发生错误',
                'error': str(e),
                'trace': traceback.format_exc()
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET', 'PUT', 'DELETE'])
def message_detail(request, pk):
    """
    获取、更新或删除单条消息。
    """
    try:
        message = Message.objects.get(message_id=pk)
    except Message.DoesNotExist:
        return Response({'code': 404, 'message': '消息不存在'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        try:
            # 尝试获取发送者信息
            sender_name = "未知"
            if message.sender_user_id:
                try:
                    sender = User.objects.get(user_id=message.sender_user_id)
                    sender_name = sender.username
                except User.DoesNotExist:
                    pass  # 如果找不到发送者，使用默认的"未知"

            # 计算阅读量
            read_count = MessageReceipt.objects.filter(message=message, read_status=True).count()

            # 获取广播状态
            broadcast_status = '待处理'  # 默认值
            try:
                broadcast = MessageBroadcast.objects.get(message_id=message.message_id)
                broadcast_status = broadcast.status
            except MessageBroadcast.DoesNotExist:
                pass

            # 构建详细响应数据
            message_data = {
                'id': message.message_id,
                'title': message.title,
                'content': message.content,
                'message_type': message.message_type,
                'publish_time': message.publish_time.strftime('%Y-%m-%d %H:%M:%S') if message.publish_time else None,
                'valid_from': message.valid_from.strftime('%Y-%m-%d %H:%M:%S') if message.valid_from else None,
                'valid_until': message.valid_until.strftime('%Y-%m-%d %H:%M:%S') if message.valid_until else None,
                'sender_user_id': message.sender_user_id,
                'sender_name': sender_name,
                'broadcast_status': broadcast_status,
                'read_count': read_count,
                'created_at': message.created_at.strftime('%Y-%m-%d %H:%M:%S') if message.created_at else None,
                'updated_at': message.updated_at.strftime('%Y-%m-%d %H:%M:%S') if message.updated_at else None
            }

            return Response({
                'code': 200,
                'message': '获取消息详情成功',
                'data': message_data
            })
        except Exception as e:
            return Response({
                'code': 500,
                'message': '服务器在处理消息详情时发生错误',
                'error': str(e),
                'trace': traceback.format_exc()
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'PUT':
        try:
            # 获取请求数据
            title = request.data.get('title')
            content = request.data.get('content')
            message_type = request.data.get('message_type')
            valid_from = request.data.get('valid_from')
            valid_until = request.data.get('valid_until')

            # 更新消息字段
            if title is not None:
                message.title = title
            if content is not None:
                message.content = content
            if message_type is not None:
                message.message_type = message_type
            if valid_from is not None:
                message.valid_from = valid_from
            if valid_until is not None:
                message.valid_until = valid_until

            # 保存更新
            message.save()

            return Response({
                'code': 200,
                'message': '消息更新成功',
                'data': {
                    'id': message.message_id,
                    'title': message.title
                }
            })
        except Exception as e:
            return Response({
                'code': 500,
                'message': '服务器在更新消息时发生错误',
                'error': str(e),
                'trace': traceback.format_exc()
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'DELETE':
        try:
            message.delete()
            return Response({
                'code': 200,
                'message': '消息删除成功'
            })
        except Exception as e:
            return Response({
                'code': 500,
                'message': '服务器在删除消息时发生错误',
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
def publish_message(request, pk):
    """
    发布草稿通知。
    """
    try:
        # 获取消息
        message = Message.objects.get(message_id=pk)
    except Message.DoesNotExist:
        return Response({'code': 404, 'message': '消息不存在'}, status=status.HTTP_404_NOT_FOUND)

    try:
        # 检查是否为草稿状态
        if message.publish_time is not None:
            return Response({
                'code': 400,
                'message': '此消息已发布，无法重复发布'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 获取请求数据
        target_groups = request.data.get('target_groups', [])
        specific_users = request.data.get('specific_users', [])

        # 如果请求中没有提供目标受众，则尝试从现有的广播记录中获取
        if not target_groups and not specific_users:
            try:
                existing_broadcast = MessageBroadcast.objects.get(message_id=message.message_id)
                target_criteria = existing_broadcast.target_criteria
                target_groups = target_criteria.get('target_groups', [])
                specific_users = target_criteria.get('specific_users', [])
            except MessageBroadcast.DoesNotExist:
                return Response({
                    'code': 400,
                    'message': '未提供目标受众，且无法获取已有的目标受众信息'
                }, status=status.HTTP_400_BAD_REQUEST)

        # 如果还是没有目标受众，返回错误
        if not target_groups and not specific_users:
            return Response({
                'code': 400,
                'message': '请至少选择一个目标群体或特定用户'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 更新消息的publish_time为当前时间
        now = timezone.now()
        message.publish_time = now
        message.save()

        # 创建消息广播记录
        target_criteria = {
            'target_groups': target_groups,
            'specific_users': specific_users
        }

        # 准备处理日志信息
        now_str = now.strftime('%Y-%m-%d %H:%M:%S')
        log_entry = f"[{now_str}] 通知已从草稿状态发布，目标受众: {len(target_groups)}个群体, {len(specific_users)}个特定用户"

        # 尝试获取现有的广播记录，如果存在则更新，否则创建新记录
        try:
            broadcast = MessageBroadcast.objects.get(message_id=message.message_id)
            broadcast.target_criteria = target_criteria
            broadcast.status = '已发布'
            broadcast.completed_at = now

            # 更新处理日志
            if broadcast.processing_log:
                broadcast.processing_log = f"{broadcast.processing_log}\n{log_entry}"
            else:
                broadcast.processing_log = log_entry

        except MessageBroadcast.DoesNotExist:
            broadcast = MessageBroadcast(
                message_id=message.message_id,
                target_criteria=target_criteria,
                status='已发布',
                completed_at=now,
                processing_log=log_entry  # 设置初始处理日志
            )
        broadcast.save()

        # 为特定用户创建消息接收记录
        if specific_users:
            for user_id_str in specific_users:
                try:
                    # 检查不同格式的用户ID
                    if isinstance(user_id_str, str) and user_id_str.startswith('user'):
                        # 尝试提取数字部分，处理"user1", "user_1"等格式
                        numeric_part = re.search(r'\d+', user_id_str)
                        if numeric_part:
                            user_id = int(numeric_part.group())
                            # 检查是否已有接收记录
                            if not MessageReceipt.objects.filter(message_id=message.message_id,
                                                                 user_id=user_id).exists():
                                receipt = MessageReceipt(
                                    message_id=message.message_id,
                                    broadcast_id=broadcast.broadcast_id,
                                    user_id=user_id,
                                    read_status=False
                                )
                                receipt.save()
                    elif isinstance(user_id_str, str) and user_id_str.startswith('comp'):
                        # 对企业用户进行特殊处理
                        # 这里可以根据企业ID查找该企业下的所有用户
                        pass  # 企业用户处理逻辑待实现
                    else:
                        # 直接尝试将整个ID作为用户ID使用
                        try:
                            if isinstance(user_id_str, int):
                                user_id = user_id_str
                            else:
                                user_id = int(user_id_str)
                            # 检查是否已有接收记录
                            if not MessageReceipt.objects.filter(message_id=message.message_id,
                                                                 user_id=user_id).exists():
                                receipt = MessageReceipt(
                                    message_id=message.message_id,
                                    broadcast_id=broadcast.broadcast_id,
                                    user_id=user_id,
                                    read_status=False
                                )
                                receipt.save()
                        except (ValueError, TypeError):
                            pass  # 忽略无法处理的用户ID格式
                except Exception:
                    pass  # 忽略处理单个用户ID时的错误

        return Response({
            'code': 200,
            'message': '通知发布成功',
            'data': {
                'id': message.message_id,
                'title': message.title,
                'publish_time': message.publish_time.strftime('%Y-%m-%d %H:%M:%S'),
                'target_groups': target_groups,
                'specific_users': specific_users
            }
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在发布通知时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# Dashboard统计接口
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def latest_messages(request):
    """获取最新通知"""
    limit = int(request.query_params.get('limit', 5))

    # 直接使用Message模型查询已发布的消息
    messages = Message.objects.filter(
        publish_time__isnull=False
    ).order_by('-publish_time')[:limit]

    data = []
    for message in messages:
        data.append({
            'id': message.message_id,
            'title': message.title,
            'publishTime': message.publish_time.strftime('%Y-%m-%d %H:%M:%S') if message.publish_time else None,
            'content': message.content[:100] + '...' if len(message.content) > 100 else message.content
        })

    return Response(data)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def announcement_list(request):
    """
    获取园区公告列表。
    """
    try:
        # 获取查询参数
        page = int(request.query_params.get('page', 1))
        size = int(request.query_params.get('size', 10))
        ignore_validity = request.query_params.get('ignore_validity', 'false').lower() == 'true'

        # 构建查询集 - 只获取类型为"园区公告"的消息
        queryset = Message.objects.filter(
            message_type='园区公告',
            publish_time__isnull=False,  # 确保只获取已发布的消息
        )
        
        # 如果不忽略有效期，则添加有效期筛选条件
        if not ignore_validity:
            now = timezone.now()
            queryset = queryset.filter(
                valid_from__lte=now,  # 确保消息在有效期内
                valid_until__gte=now
            )
            
        queryset = queryset.order_by('-publish_time')

        # 获取总数
        total = queryset.count()

        # 分页处理
        start = (page - 1) * size
        end = start + size
        paginated_messages = queryset[start:end]

        # 构建响应数据
        announcements = []
        for message in paginated_messages:
            # 检查当前用户是否已读此消息
            read_status = False
            try:
                receipt = MessageReceipt.objects.get(
                    message_id=message.message_id,
                    user_id=request.user.user_id
                )
                read_status = receipt.read_status
            except MessageReceipt.DoesNotExist:
                pass

            announcements.append({
                'id': message.message_id,
                'title': message.title,
                'content': message.content,
                'publish_time': message.publish_time.strftime('%Y-%m-%d %H:%M:%S') if message.publish_time else None,
                'read_status': read_status,
                'sender_name': message.sender_user.username if message.sender_user else '系统'
            })

        return Response({
            'code': 200,
            'message': '获取园区公告列表成功',
            'data': {
                'total': total,
                'list': announcements,
                'page': page,
                'size': size,
                'pages': (total + size - 1) // size  # 总页数计算
            }
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在处理园区公告列表时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def announcement_detail(request, pk):
    """
    获取消息详情。
    支持所有类型的消息，不再限制只能查看"园区公告"类型。
    """
    try:
        # 获取消息，不限制消息类型
        message = Message.objects.get(message_id=pk)

        # 检查消息是否已发布
        if not message.publish_time:
            return Response({
                'code': 404,
                'message': '该消息不存在或未发布'
            }, status=status.HTTP_404_NOT_FOUND)

        # 更新或创建消息回执
        receipt, created = MessageReceipt.objects.get_or_create(
            message_id=pk,
            user_id=request.user.user_id,
            defaults={
                'read_status': True,
                'read_time': timezone.now()
            }
        )

        # 如果回执已存在但未标记为已读，则更新为已读
        if not created and not receipt.read_status:
            receipt.read_status = True
            receipt.read_time = timezone.now()
            receipt.save()

        # 构建响应数据
        announcement_data = {
            'id': message.message_id,
            'title': message.title,
            'content': message.content,
            'publish_time': message.publish_time.strftime('%Y-%m-%d %H:%M:%S') if message.publish_time else None,
            'valid_from': message.valid_from.strftime('%Y-%m-%d %H:%M:%S') if message.valid_from else None,
            'valid_until': message.valid_until.strftime('%Y-%m-%d %H:%M:%S') if message.valid_until else None,
            'sender_name': message.sender_user.username if message.sender_user else '系统'
        }

        return Response({
            'code': 200,
            'message': '获取消息详情成功',
            'data': announcement_data
        })
    except Message.DoesNotExist:
        return Response({
            'code': 404,
            'message': '消息不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在处理消息详情时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def consultation_list(request):
    """
    获取园区咨询列表。
    包括"园区资讯"、"新闻资讯"和"活动推广"类型的消息。
    """
    try:
        # 获取查询参数
        page = int(request.query_params.get('page', 1))
        size = int(request.query_params.get('size', 10))
        ignore_validity = request.query_params.get('ignore_validity', 'false').lower() == 'true'

        # 构建查询集 - 获取类型为"园区资讯"、"新闻资讯"和"活动推广"的消息
        queryset = Message.objects.filter(
            message_type__in=['园区资讯', '新闻资讯', '活动推广'],
            publish_time__isnull=False,  # 确保只获取已发布的消息
        )
        
        # 如果不忽略有效期，则添加有效期筛选条件
        if not ignore_validity:
            now = timezone.now()
            queryset = queryset.filter(
                valid_from__lte=now,  # 确保消息在有效期内
                valid_until__gte=now
            )
            
        queryset = queryset.order_by('-publish_time')

        # 获取总数
        total = queryset.count()

        # 分页处理
        start = (page - 1) * size
        end = start + size
        paginated_messages = queryset[start:end]

        # 构建响应数据
        consultations = []
        for message in paginated_messages:
            # 检查当前用户是否已读此消息
            read_status = False
            try:
                receipt = MessageReceipt.objects.get(
                    message_id=message.message_id,
                    user_id=request.user.user_id
                )
                read_status = receipt.read_status
            except MessageReceipt.DoesNotExist:
                pass

            consultations.append({
                'id': message.message_id,
                'title': message.title,
                'content': message.content,
                'publish_time': message.publish_time.strftime('%Y-%m-%d %H:%M:%S') if message.publish_time else None,
                'read_status': read_status,
                'message_type': message.message_type,  # 添加消息类型字段
                'sender_name': message.sender_user.username if message.sender_user else '系统'
            })

        return Response({
            'code': 200,
            'message': '获取园区资讯列表成功',
            'data': {
                'total': total,
                'list': consultations,
                'page': page,
                'size': size,
                'pages': (total + size - 1) // size  # 总页数计算
            }
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在处理园区资讯列表时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def consultation_detail(request, pk):
    """
    获取园区资讯详情。
    """
    try:
        # 获取消息
        message = Message.objects.get(
            message_id=pk, 
            message_type__in=['园区资讯', '新闻资讯', '活动推广']
        )

        # 检查消息是否已发布
        if not message.publish_time:
            return Response({
                'code': 404,
                'message': '该资讯不存在或未发布'
            }, status=status.HTTP_404_NOT_FOUND)

        # 更新或创建消息回执
        receipt, created = MessageReceipt.objects.get_or_create(
            message_id=pk,
            user_id=request.user.user_id,
            defaults={
                'read_status': True,
                'read_time': timezone.now()
            }
        )

        # 如果回执已存在但未标记为已读，则更新为已读
        if not created and not receipt.read_status:
            receipt.read_status = True
            receipt.read_time = timezone.now()
            receipt.save()

        # 构建响应数据
        consultation_data = {
            'id': message.message_id,
            'title': message.title,
            'content': message.content,
            'message_type': message.message_type,  # 添加消息类型字段
            'publish_time': message.publish_time.strftime('%Y-%m-%d %H:%M:%S') if message.publish_time else None,
            'valid_from': message.valid_from.strftime('%Y-%m-%d %H:%M:%S') if message.valid_from else None,
            'valid_until': message.valid_until.strftime('%Y-%m-%d %H:%M:%S') if message.valid_until else None,
            'sender_name': message.sender_user.username if message.sender_user else '系统'
        }

        return Response({
            'code': 200,
            'message': '获取园区资讯详情成功',
            'data': consultation_data
        })
    except Message.DoesNotExist:
        return Response({
            'code': 404,
            'message': '资讯不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在处理园区资讯详情时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_messages(request):
    """
    获取当前用户的特定消息列表。
    这些消息是专门发送给当前用户的，如审批提醒、业务提醒等。
    """
    try:
        # 获取查询参数
        page = int(request.query_params.get('page', 1))
        size = int(request.query_params.get('size', 10))
        message_type = request.query_params.get('message_type', None)
        ignore_validity = request.query_params.get('ignore_validity', 'false').lower() == 'true'

        # 获取当前用户ID
        current_user_id = request.user.user_id

        # 构建查询集 - 通过消息回执表查询发送给当前用户的消息
        receipt_queryset = MessageReceipt.objects.filter(
            user_id=current_user_id
        ).select_related('message')

        # 如果指定了消息类型，进一步筛选
        if message_type:
            receipt_queryset = receipt_queryset.filter(message__message_type=message_type)
            
        # 如果不忽略有效期，则添加有效期筛选条件
        if not ignore_validity:
            now = timezone.now()
            receipt_queryset = receipt_queryset.filter(
                message__valid_from__lte=now,  # 确保消息在有效期内
                message__valid_until__gte=now
            )

        # 按消息发布时间倒序排序
        receipt_queryset = receipt_queryset.order_by('-message__publish_time')

        # 获取总数
        total = receipt_queryset.count()

        # 分页处理
        start = (page - 1) * size
        end = start + size
        paginated_receipts = receipt_queryset[start:end]

        # 构建响应数据
        user_messages = []
        for receipt in paginated_receipts:
            message = receipt.message
            user_messages.append({
                'id': message.message_id,
                'title': message.title,
                'content': message.content,
                'message_type': message.message_type,
                'publish_time': message.publish_time.strftime('%Y-%m-%d %H:%M:%S') if message.publish_time else None,
                'read_status': receipt.read_status,
                'read_time': receipt.read_time.strftime('%Y-%m-%d %H:%M:%S') if receipt.read_time else None,
                'sender_name': message.sender_user.username if message.sender_user else '系统'
            })

        return Response({
            'code': 200,
            'message': '获取用户消息列表成功',
            'data': {
                'total': total,
                'list': user_messages,
                'page': page,
                'size': size,
                'pages': (total + size - 1) // size  # 总页数计算
            }
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在处理用户消息列表时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def feedback_list(request):
    """
    获取问题反馈列表
    """
    try:
        status_param = request.query_params.get('status', None)
        page = int(request.query_params.get('page', 1))
        size = int(request.query_params.get('size', 10))

        queryset = Feedback.objects.all()
        if status_param:
            queryset = queryset.filter(status=status_param)

        total = queryset.count()
        start = (page - 1) * size
        end = start + size
        queryset = queryset.order_by('-created_at')[start:end]

        feedbacks = []
        for fb in queryset:
            feedbacks.append({
                'id': fb.feedback_id,
                'feedback_id': fb.feedback_id,
                'title': fb.title,
                'status': fb.status,
                'content': fb.content,
                'created_at': fb.created_at.strftime('%Y-%m-%d %H:%M:%S') if fb.created_at else None,
                'user_id': fb.user_id,
                'visitor_id': fb.visitor_id
            })

        return Response({
            'code': 200,
            'message': '获取反馈列表成功',
            'data': {
                'total': total,
                'list': feedbacks,
                'page': page,
                'size': size,
                'pages': (total + size - 1) // size
            }
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在处理反馈列表时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_feedback(request):
    """
    创建新的问题反馈
    """
    try:
        # 获取当前用户
        current_user = request.user

        # 获取请求数据
        title = request.data.get('title')
        content = request.data.get('content')
        media_urls = request.data.get('media_urls')

        # 验证必填字段
        if not title or not content:
            return Response({
                'code': 400,
                'message': '标题和内容为必填项'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 创建新的反馈记录
        feedback = Feedback.objects.create(
            user=current_user,
            title=title,
            content=content,
            media_urls=media_urls,
            status='PENDING'
        )

        # 构建响应数据
        feedback_data = {
            'feedback_id': feedback.feedback_id,
            'id': feedback.feedback_id,  # 添加id字段，与前端兼容
            'title': feedback.title,
            'content': feedback.content,
            'media_urls': feedback.media_urls,
            'status': feedback.status,
            'created_at': feedback.created_at.strftime('%Y-%m-%d %H:%M:%S') if feedback.created_at else None
        }

        return Response({
            'code': 201,
            'message': '提交反馈成功',
            'data': feedback_data
        }, status=status.HTTP_201_CREATED)

    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在处理反馈提交时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET', 'PUT'])
@permission_classes([IsAuthenticated])
def feedback_detail(request, pk):
    """
    获取或更新单条反馈
    """
    try:
        fb = Feedback.objects.get(pk=pk)
    except Feedback.DoesNotExist:
        return Response({'code': 404, 'message': '反馈不存在'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        data = {
            'id': fb.feedback_id,
            'feedback_id': fb.feedback_id,
            'title': fb.title,
            'content': fb.content,
            'media_urls': fb.media_urls,
            'status': fb.status,
            'handler_id': fb.handler_id,
            'handle_result': fb.handle_result,
            'created_at': fb.created_at.strftime('%Y-%m-%d %H:%M:%S') if fb.created_at else None,
            'user_id': fb.user_id,
            'visitor_id': fb.visitor_id
        }
        return Response({'code': 200, 'message': '获取反馈详情成功', 'data': data})

    elif request.method == 'PUT':
        status_param = request.data.get('status', None)
        handle_result = request.data.get('handle_result', None)
        handler_id = request.data.get('handler_id', None)
        title = request.data.get('title', None)
        content = request.data.get('content', None)
        media_urls = request.data.get('media_urls', None)

        update_fields = []

        if status_param:
            fb.status = status_param
            update_fields.append('status')

        if handle_result:
            fb.handle_result = handle_result
            update_fields.append('handle_result')

        if handler_id:
            fb.handler_id = handler_id
            update_fields.append('handler')

        if title:
            fb.title = title
            update_fields.append('title')

        if content:
            fb.content = content
            update_fields.append('content')

        if media_urls:
            fb.media_urls = media_urls
            update_fields.append('media_urls')

        fb.save(update_fields=update_fields)

        return Response({'code': 200, 'message': '更新反馈成功'})


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_feedback(request, pk):
    """
    删除问题反馈
    """
    try:
        feedback = Feedback.objects.get(pk=pk)

        # 检查权限：只有反馈的创建者或管理员可以删除
        if feedback.user_id != request.user.user_id and not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '您没有权限删除此反馈'
            }, status=status.HTTP_403_FORBIDDEN)

        feedback.delete()

        return Response({
            'code': 204,
            'message': '删除反馈成功'
        }, status=status.HTTP_204_NO_CONTENT)

    except Feedback.DoesNotExist:
        return Response({
            'code': 404,
            'message': '反馈不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': '服务器在处理反馈删除时发生错误',
            'error': str(e),
            'trace': traceback.format_exc()
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
